// import {App, inject, reactive} from "vue";
// import defaultConfig, {DefaultConfig} from "@/config/defaultConfig";
// import Components from './component';
// import {devFilterMethods, devMethods, DevMethods, devProvideMethods} from '@/utils';
// import { INSTALLED_KEY } from '@/constants'
//
// const CONFIG_KEY = Symbol('devecoui-config');
//
// export const useConfig = (): DefaultConfig => {
//     const config = inject(CONFIG_KEY);
//     if (!config) {
//         return defaultConfig;
//     }
//     return config as DefaultConfig;
// };
//
// export const createConfig = (customConfig = {}) => {
//     return reactive({...defaultConfig, ...customConfig});
// };
//
// const install = (app: App, options?: Partial<DefaultConfig>) => {
//     if (app[INSTALLED_KEY]) return;
//     app[INSTALLED_KEY] = true;
//     const config = createConfig(options);// 组件配置
//     const mergedConfig = devFilterMethods({ ...defaultConfig, ...options }, devMethods as DevMethods);// 过滤出可自定义的方法
//     devProvideMethods(app, mergedConfig);// 注册可自定义方法
//     app.provide(CONFIG_KEY, config);
//     Components.forEach((c) => app.use(c));
// };
//
// const DevecoUI = {
//     install,
// };
//
// export default DevecoUI;



import { inject, reactive } from 'vue';
import defaultConfig, { DefaultConfig } from '@/config/defaultConfig';
import { App } from 'vue';
import Components from './component';
import { devFilterMethods, devMethods, DevMethods, devProvideMethods } from '@/utils';
import { INSTALLED_KEY } from '@/constants';

const CONFIG_KEY = Symbol('devecoui-config');

let cachedConfig: DefaultConfig | null = null;

/**
 * 获取配置对象，具有惰性缓存机制，避免 setup 之外调用 inject() 报错。
 */
export const useConfig = (): DefaultConfig => {
    if (!cachedConfig) {
        try {
            const config = inject(CONFIG_KEY);
            cachedConfig = config ? (config as DefaultConfig) : defaultConfig;
        } catch (e) {
            cachedConfig = defaultConfig;
        }
    }
    return cachedConfig;
};

/**
 * 创建配置对象（合并用户配置）
 */
export const createConfig = (customConfig = {}) => {
    return reactive({ ...defaultConfig, ...customConfig });
};

/**
 * UI库安装方法
 */
const install = (app: App, options?: Partial<DefaultConfig>) => {
    if ((app as any)[INSTALLED_KEY]) return;
    (app as any)[INSTALLED_KEY] = true;

    const config = createConfig(options); // 响应式配置
    const mergedConfig = devFilterMethods(
        { ...defaultConfig, ...options },
        devMethods as DevMethods
    ); // 过滤出可重写的方法

    devProvideMethods(app, mergedConfig); // 全局注入方法
    app.provide(CONFIG_KEY, config); // 提供配置对象
    Components.forEach((c) => app.use(c)); // 注册组件
};

const DevecoUI = {
    install,
};

export default DevecoUI;

